package com.example.controller;

import com.example.entity.Teacher;
import com.example.entity.User;
import com.example.entity.Student;
import com.example.service.TeacherService;
import com.example.service.StudentService;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/teacher")
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    @ResponseBody
    public List<Teacher> getAllTeachers(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user.getRole().equals("ADMIN")) {
            return teacherService.getAllTeachers();
        } else if (user.getRole().equals("TEACHER")) {
            // 教师只能查看自己的信息
            return Collections.singletonList(teacherService.getTeacherById(user.getUsername()));
        }
        return Collections.emptyList();
    }

    @GetMapping("/{id}")
    @ResponseBody
    public Teacher getTeacherById(@PathVariable String id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user.getRole().equals("ADMIN") || user.getUsername().equals(id)) {
            return teacherService.getTeacherById(id);
        }
        return null;
    }

    @GetMapping("/class-info")
    @ResponseBody
    public Map<String, Object> getClassInfo(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        User user = (User) session.getAttribute("user");
        if (user.getRole().equals("TEACHER")) {
            Teacher teacher = teacherService.getTeacherById(user.getUsername());
            if (teacher != null && teacher.getClassManaged() != null) {
                List<Student> students = studentService.findByClass(teacher.getClassManaged());
                result.put("success", true);
                result.put("data", students);
            } else {
                result.put("success", false);
                result.put("message", "未找到管理的班级");
            }
        } else {
            result.put("success", false);
            result.put("message", "权限不足");
        }
        return result;
    }

    @PostMapping("/update-grade")
    @ResponseBody
    public Map<String, Object> updateGrade(@RequestBody Map<String, Object> params, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        User user = (User) session.getAttribute("user");
        if (user.getRole().equals("TEACHER")) {
            Teacher teacher = teacherService.getTeacherById(user.getUsername());
            if (teacher != null && teacher.getClassManaged() != null) {
                String studentId = (String) params.get("studentId");
                Student student = studentService.findByStudentId(studentId);
                if (student != null && student.getStuClass().equals(teacher.getClassManaged())) {
                    Integer midMarks = (Integer) params.get("midMarks");
                    Integer endMarks = (Integer) params.get("endMarks");
                    student.setMidMarks(midMarks != null ? new BigDecimal(midMarks) : null);
                    student.setEndMarks(endMarks != null ? new BigDecimal(endMarks) : null);
                    studentService.updateStudent(student);
                    result.put("success", true);
                    result.put("message", "成绩更新成功");
                } else {
                    result.put("success", false);
                    result.put("message", "该学生不属于您管理的班级");
                }
            } else {
                result.put("success", false);
                result.put("message", "未找到管理的班级");
            }
        } else {
            result.put("success", false);
            result.put("message", "权限不足");
        }
        return result;
    }

    @PostMapping("/add")
    @ResponseBody
    public Map<String, Object> addTeacher(@RequestBody Teacher teacher, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        User user = (User) session.getAttribute("user");
        if (user.getRole().equals("ADMIN")) {
            boolean success = teacherService.addTeacher(teacher);
            User newUser = new User();
            newUser.setUsername(teacher.getTeacherId());
            newUser.setPassword("123456");
            newUser.setRole("TEACHER");
            userService.addUser(newUser);
            result.put("success", success);
            result.put("message", success ? "添加成功" : "添加失败");
        } else {
            result.put("success", false);
            result.put("message", "权限不足");
        }
        return result;
    }

    @PutMapping("/update")
    @ResponseBody
    public Map<String, Object> updateTeacher(@RequestBody Teacher teacher, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        User user = (User) session.getAttribute("user");
        if (user.getRole().equals("ADMIN") || user.getUsername().equals(teacher.getTeacherId())) {
            boolean success = teacherService.updateTeacher(teacher);
            result.put("success", success);
            result.put("message", success ? "更新成功" : "更新失败");
        } else {
            result.put("success", false);
            result.put("message", "权限不足");
        }
        return result;
    }

    @DeleteMapping("/{id}")
    @ResponseBody
    public Map<String, Object> deleteTeacher(@PathVariable String id, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        User user = (User) session.getAttribute("user");
        if (user.getRole().equals("ADMIN")) {
            User newUser = userService.findByUsername(id);
            userService.deleteUser(newUser.getId());
            boolean success = teacherService.deleteTeacher(id);
            result.put("success", success);
            result.put("message", success ? "删除成功" : "删除失败");
        } else {
            result.put("success", false);
            result.put("message", "权限不足");
        }
        return result;
    }
} 